package com.pktechan.manage.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.pktechan.manage.base.annotation.Auth;
import com.pktechan.manage.base.annotation.RecordOperateLog;
import com.pktechan.manage.entity.SysUser;
import com.pktechan.manage.exception.CustomException;
import com.pktechan.manage.service.SysRoleService;
import com.pktechan.manage.service.SysUserService;
import com.pktechan.manage.utils.EncrptUtil;
import com.pktechan.manage.utils.HtmlUtil;
import com.pktechan.manage.utils.SessionUtils;
import com.pktechan.manage.vo.SysUserVO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.Map;

/**
 * @description:
 * @author: s.zhangbj03307
 * @create: 2021/3/24 9:59
 **/
@Controller
@RequestMapping("sysUser")
public class SysUserContorller {
    private static final Logger logger = LoggerFactory.getLogger(SysUserContorller.class);

    @Autowired
    private SysUserService sysUserService;
    @Autowired
    private SysRoleService sysRoleService;

    /**
     * 打开用户列表页面
     * @return
     */
    @RequestMapping("toUsersList")
    public String toUsersList() {
        return "user/userList";
    }
    /**
     * 查看用户页面
     * @return
     */
    @RequestMapping("toQueryUser")
    public String toQueryUser() {
        return "user/userQuery";
    }
    /**
     * 修改用户页面
     * @return
     */
    @RequestMapping("toUpdateUser")
    public String toUpdateUser() {
        return "user/userUpdate";
    }
    /**
     * 修改密码
     * @return
     */
    @RequestMapping("userUpdatePassWord")
    public String userUpdatePassWord() {
        return "user/userUpdatePassWord";
    }
    /**
     * 获取员工基本信息列表。
     *
     * @param sysUser 员工及角色过滤条件。
     *              TA清算
     */
    @RequestMapping(value = "/usersList", method = RequestMethod.POST)
    public void getUserList(@RequestBody SysUser sysUser, HttpServletRequest request,
                            HttpServletResponse response) {
        try {
            logger.info("================== 获取员工基本信息列表 ==================");
            PageHelper.startPage(sysUser.getPageNo(), sysUser.getPageSize());
            List<SysUser> list = sysUserService.getList(sysUser);
            PageInfo pageInfo = new PageInfo(list);
            HtmlUtil.writerSuccessJson(response, pageInfo);
        } catch (CustomException eme) {
            HtmlUtil.writerFailJson(response, eme.getMessage());
            logger.debug(eme.getMessage());
        } catch (Exception e) {
            HtmlUtil.writerFailJson(response, e.getMessage());
            logger.error(e.getMessage(), e);
        }
    }
    /**
     * 重置用户密码
     *
     * @param sysUser TA
     */
    @RequestMapping(value = "/resetPwd", method = RequestMethod.POST)
    public void resetPwd(@RequestBody SysUser sysUser, HttpServletRequest request, HttpServletResponse response) {
        try {
            logger.info("================== sysUser reset Pwd==================");
            //密码重置：6位随机数字
            int i = (int) ((Math.random() * 9 + 1) * 100000);
            sysUser.setPassword(String.valueOf(i));
            sysUserService.updateSystemUserPwd(sysUser);
            HtmlUtil.writerSuccessJson(response, i);
        } catch (CustomException eme) {
            HtmlUtil.writeFallJsonByKey(request, response, eme.getMessage(), null);
            logger.debug(eme.getMessage());
        } catch (Exception e) {
            HtmlUtil.writerFailJson(response, e.getMessage());
            logger.error(e.getMessage(), e);
        }
    }
    /**
     * 逻辑删除用户。用户不能设置自己的逻辑删除
     *
     * @param user TA清算
     */
    @RequestMapping(value = "/deleteUser", method = RequestMethod.POST)
    public void deleteUserById(@RequestBody SysUser user, HttpServletRequest request,
                               HttpServletResponse response) {
        try {
            logger.info("================== sysUser delete ==================");
            //判断登录用户与所选用户 ID是否一致 一致则不能删除
            int id = SessionUtils.getUser(request).getId();
            int userId = user.getId();
            if (id != userId) {
                if (isCurrentUser(request, userId)) {
                    HtmlUtil.writeFallJsonByKey(request, response, "user.canNotDeleteHimSelf", null);
                    logger.debug("user.canNotDeleteHimSelf");
                    return;
                }
                sysRoleService.deleteAllRoleByUser(userId);
                sysUserService.deleteSystemUser(userId);
                HtmlUtil.writerSuccessJson(response);
            } else {
                HtmlUtil.writerFailJson(response);
            }
        } catch (CustomException eme) {
            HtmlUtil.writeFallJsonByKey(request, response, eme.getMessage(), null);
            logger.debug(eme.getMessage());
        } catch (Exception e) {
            HtmlUtil.writerFailJson(response, e.getMessage());
            logger.error(e.getMessage(), e);
        }
    }

    /**
     * 判断是否是当前登录用户
     *
     * @param request
     * @param userId
     * @return
     */
    protected boolean isCurrentUser(HttpServletRequest request, Integer userId) {
        SysUser sysUser = SessionUtils.getUser(request);
        if (sysUser != null) {
            return sysUser.getId().equals(userId);
        } else {
            return false;
        }
    }

    /**
     * 批量删除操作
     * TA清算
     */
    @RequestMapping(value = "/deleteUserAll", method = RequestMethod.POST)
    public void deleteUserAll(@RequestBody SysUserVO user, HttpServletRequest request,
                              HttpServletResponse response) {
        try {
            logger.info("================== sysUser delete ==================");
            int id = SessionUtils.getUser(request).getId();
            boolean flag = sysUserService.deleteUserAll(user, id);
            if (flag) {
                HtmlUtil.writerSuccessJson(response);
            } else {
                HtmlUtil.writerFailJson(response);
            }
        } catch (CustomException eme) {
            HtmlUtil.writeFallJsonByKey(request, response, eme.getMessage(), null);
            logger.debug(eme.getMessage());
        } catch (Exception e) {
            HtmlUtil.writerFailJson(response, e.getMessage());
            logger.error(e.getMessage(), e);
        }
    }
    /**
     * 根据指定员工唯一标识获取基本信息。
     *
     * @param sysUser TA清算。
     */
    @RequestMapping(value = "/queryOneByUserId", method = RequestMethod.POST)
    public void getUserById(@RequestBody SysUser sysUser, HttpServletRequest request,
                            HttpServletResponse response) {
        try {
            logger.info("================== sysUser query ==================");
            Map user = sysUserService.getSystemUserList(sysUser);
            HtmlUtil.writerSuccessJson(response, user);
        } catch (CustomException eme) {
            HtmlUtil.writeFallJsonByKey(request, response, eme.getMessage(), null);
            logger.debug(eme.getMessage());
        } catch (Exception e) {
            HtmlUtil.writerFailJson(response, e.getMessage());
            logger.error(e.getMessage(), e);
        }
    }
    /**
     * 更新员工基本信息列表,用户不能将自己设置为超级管理员
     *
     * @param user TA清算
     */
    @RequestMapping(value = "/updateUser", method = RequestMethod.POST)
    public void setUser(@RequestBody SysUserVO user, HttpServletRequest request, HttpServletResponse response) {
        try {
            logger.info("================== sysUser update ==================");
            sysUserService.updateSystemUser(user);
            //判断是否为超级管理员
            if (user.getSuperAdmin() != 1) {
                sysRoleService.updateUserRole(user);
            }
            HtmlUtil.writerSuccessJson(response);
        } catch (CustomException eme) {
            HtmlUtil.writeFallJsonByKey(request, response, eme.getMessage(), null);
            logger.debug(eme.getMessage());
        } catch (Exception e) {
            HtmlUtil.writerFailJson(response, e.getMessage());
            logger.error(e.getMessage(), e);
        }
    }
    /**
     * 更新自身密码
     *
     * @param user TA清算
     */
    @RequestMapping(value = "/updatePwd", method = RequestMethod.POST)
    public void updatePwd(@RequestBody SysUserVO user, HttpServletRequest request, HttpServletResponse response) {
        try {
            logger.info("================== sysUser update Pwd==================");
            if (EncrptUtil.encryptMD5(user.getOldPassword()).equals((SessionUtils.getUser(request).getPassword()))) {
                SysUser sysUser = new SysUser();
                sysUser.setId(SessionUtils.getUser(request).getId());
                //新密码
                sysUser.setPassword(EncrptUtil.encryptMD5(user.getPassword()));
                sysUserService.update(sysUser);
                HtmlUtil.writerSuccessJson(response, "修改成功!");
            } else {
                HtmlUtil.writerFailJson(response, "原始密码不正确");
            }
        } catch (CustomException eme) {
            HtmlUtil.writeFallJsonByKey(request, response, eme.getMessage(), null);
            logger.debug(eme.getMessage());
        } catch (Exception e) {
            HtmlUtil.writerFailJson(response, e.getMessage());
            logger.error(e.getMessage(), e);
        }
    }
}
